package com.eh.iteratorAndComposition.iterator;

import com.eh.iteratorAndComposition.base.MenuComponent;

import java.util.Iterator;

/**
 * Created by David on 2016/5/1.
 */
public class ArrayIterator implements Iterator<MenuComponent> {
    private MenuComponent[] menus;
    int position = 0;

    public ArrayIterator(MenuComponent[] menus) {
        this.menus = menus;
    }

    @Override
    public boolean hasNext() {
        if (position >= menus.length || menus[position] == null) {
            return false;
        }
        return true;
    }

    @Override
    public MenuComponent next() {
        if (hasNext()) {
            MenuComponent menuComponent = menus[position];
            position++;
            return menuComponent;
        }
        return null;
    }

    @Override
    public void remove() {
        if (menus[position - 1] != null) {
            for (int i = position - 1; i < menus.length; i++) {
                menus[i] = menus[i + 1];
            }
            menus[menus.length - 1] = null;
        }
    }
}
